<template>
  <div>
    <el-card>
      <!-- 三级分类 -->
      <CategorySelect :disabled="!isShowList" />
    </el-card>
    <el-card style="margin-top: 10px">
      <!-- 展示页 -->
      <div v-show="isShowList" v-loading="loading">
        <!-- 提交按钮 -->
        <el-button
          type="primary"
          :icon="Plus"
          @click="showAdd"
          :disabled="!category3Id"
          >添加属性</el-button
        >
        <!-- 展示表格 -->
        <el-table :data="attrList" border style="margin-top: 10px">
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          />
          <el-table-column label="属性名称" prop="attrName" width="140" />
          <el-table-column label="属性列表">
            <template #default="{ row }">
              <el-tag
                style="margin-right: 5px"
                size="small"
                v-for="item in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template v-slot="{ row, $index }">
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                @click="showUpdate(row)"
              ></el-button>
              <el-popconfirm
                :title="`确认是否要删除${row.attrName}?`"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="deleteValueList(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 编辑页 -->
      <div v-show="!isShowList">
        <div>
          <span style="margin-right: 20px">属性名</span>
          <el-input style="width: 240px" v-model="attr.attrName"></el-input>
        </div>

        <div style="margin-top: 20px">
          <el-button type="primary" :icon="Plus" @click="addValue">
            添加属性
          </el-button>
          <el-button @click="isShowList = true"> 取消 </el-button>
        </div>
        <el-table :data="attr.attrValueList" style="margin-top: 10px">
          <el-table-column
            label="序号"
            type="index"
            width="120"
            align="center"
          />
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <div v-if="row.isEdit" @click="toEdit(row)">
                <span>{{ row.valueName }}</span>
              </div>
              <el-input
                v-else
                v-model="row.valueName"
                style="width: 360px"
                ref="inputRef"
                size="small"
                @blur="toShow(row, $index)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="160">
            <template #default="{ $index }">
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="attr.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px">
          <el-button
            type="primary"
            @click="confirmValueList"
            :disabled="isDIsabled"
          >
            保存
          </el-button>
          <el-button @click="isShowList = true"> 取消 </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
  export default {
    name: "Attr",
  };
</script>

<script lang="ts" setup>
  import {
    deleteAttrApi,
    getAttrInfoListApi,
    saveAttrInfoApi,
  } from "@/api/product/attr";
  import type {
    attrValueModel,
    attrValueListModel,
    attrModel,
  } from "@/api/product/model/attrModel";
  import { useCategoryStore } from "@/stores/category";
  import { Plus, Delete, Edit } from "@element-plus/icons-vue";
  import { ElMessage, type ElInput } from "element-plus";
  import { cloneDeep } from "lodash";
  import { storeToRefs } from "pinia";
  import { ref, watch, reactive, onMounted, nextTick, computed } from "vue";

  /* **** 展示区动态渲染 **** */
  const attrList = ref<attrValueListModel>([]);
  const categoryStore = useCategoryStore();
  const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);
  const loading = ref(false);
  // 监听 一旦三级列表有值就渲染展示页
  watch(category3Id, (val) => {
    if (val) {
      getAttrList();
    } else {
      attrList.value = [];
    }
  });
  // 渲染展示页的请求
  const getAttrList = async () => {
    loading.value = true;
    attrList.value = await getAttrInfoListApi({
      category1Id: category1Id.value as number,
      category2Id: category2Id.value as number,
      category3Id: category3Id.value as number,
    });
    loading.value = false;
    // console.log(attrList);
  };
  //初始化 一旦有三级分类就渲染数据
  onMounted(() => {
    if (category3Id.value) {
      getAttrList();
    }
  });
  //展示页 删除
  const deleteValueList = async (id: number) => {
    await deleteAttrApi(id);
    // 成功之后: 提示 / 重新获取列表
    ElMessage.success("删除成功!");
    getAttrList();
  };

  /* **** 编辑区动态渲染 **** */
  // 切换展示页跟编辑页
  const initAttr = () => ({
    attrName: "",
    attrValueList: [],
    categoryId: 0,
    categoryLevel: 3,
  });
  const attr = ref<attrValueModel>(initAttr());
  const isShowList = ref(true);

  // 携带数据到编辑页 修改
  const showUpdate = (row: attrValueModel) => {
    Object.assign(attr.value, cloneDeep(row));
    attr.value.attrValueList.forEach((item) => (item.isEdit = true));
    isShowList.value = false;
  };
  //退到展示页添加
  const showAdd = () => {
    Object.assign(attr.value, initAttr());
    isShowList.value = false;
  };

  const inputRef = ref<InstanceType<typeof ElInput>>();
  //点击属性值 变input框
  const toEdit = (row: attrModel) => {
    row.isEdit = false;

    // 自动获取焦点: nextTick + input.focus()
    nextTick(() => {
      inputRef.value?.focus();
    });
  };
  const toShow = (row: attrModel, index: number) => {
    if (!row.valueName) {
      attr.value.attrValueList.splice(index, 1);
      return;
    }
    const isRepeat = attr.value.attrValueList.some(
      (item) => item != row && item.valueName === row.valueName
    );
    if (isRepeat) {
      attr.value.attrValueList.splice(index, 1);
      return;
    }

    row.isEdit = true;
  };
  //添加属性值
  const newAddValue = () => ({
    attrId: attr.value.id as number,
    valueName: "",
    isEdit: false,
  });
  const addValue = () => {
    attr.value.attrValueList.push(newAddValue());
    nextTick(() => {
      inputRef.value?.focus();
    });
  };

  //点击保存 提交数据
  const confirmValueList = async () => {
    attr.value.attrValueList.forEach((value) => delete value.isEdit);
    attr.value.categoryId = category3Id.value as number;
    await saveAttrInfoApi(attr.value);
    ElMessage.success("保存成功！");
    getAttrList();
    isShowList.value = true;
  };

  //限制保存按钮
  const isDIsabled = computed(() => {
    const isName = !!attr.value.attrName;
    const isValueName = attr.value.attrValueList.some((item) => item.valueName);

    return !isName || !isValueName;
  });
</script>

<style lang="scss" scoped></style>
